package org.company.ci.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.company.ci.domain.User;

/**
 * Filtro encargado de verificar que el usuario exista en la session.
 *  
 * @author Hudy 02/12/2010
 * @version 1.0
 */
public class LoginFilter implements Filter {
	
	private FilterConfig filterConfig;

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		filterConfig = null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		
		try {
			boolean autorizado = false;
			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) res;
			HttpSession session = request.getSession(false);
			if (session != null) {
				User usuario = (User) session.getAttribute("user_login");
				if((usuario != null)){
					autorizado = true;
				}
					
			}

			if (autorizado) {
				System.out.println("Autorizado: ");
				chain.doFilter(request, response);
			} else if (filterConfig != null) {
				ServletContext context = filterConfig.getServletContext();
				String login_page = context.getContextPath()+"/login.jsp";
				if (login_page != null && !"".equals(login_page)) {
					System.out.println("Usuario no Autorizado se redirecciona a: "+login_page);
					response.sendRedirect(login_page);
					//context.getRequestDispatcher(login_page).forward(request, response);
				}
			} else { 
				throw new ServletException ("Acceso no autorizado, forward a la pagina de login");
			}
		} catch (IOException io) {
			io.printStackTrace();
		} catch (ServletException se) {
			se.printStackTrace();
		}
			
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("Inicio del filtro Login");
		this.filterConfig = fConfig;
	}

}
